package com.cnhis.cloudhealth.clinical.clidoctor.lucence.service;

import java.nio.file.Paths;
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.xml.bind.annotation.XmlElementDecl.GLOBAL;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Autowired;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.alibaba.dubbo.config.annotation.Service;
import com.cnhis.cloudhealth.clinical.clidoctor.basicinformationquery.bo.BasicInformationQueryBo;
import com.cnhis.cloudhealth.clinical.clidoctor.clidoctor.dao.CliDoctorDao;
import com.cnhis.cloudhealth.clinical.clidoctor.lucence.bo.LucenceBo;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.util.PinYinUtilForLucence;
import com.cnhis.cloudhealth.commons.utils.GlobalVariable;
import com.cnhis.cloudhealth.commons.utils.PropDynamicCfg;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
import com.cnhis.cloudhealth.commons.utils.jpinyin.PinyinHelper;
import com.cnhis.cloudhealth.commons.utils.sorl.BaseSolr;
@Service
public class LuceneServiceImpl implements ILucenceService
{
    @Resource
    private CliDoctorDao cliDoctorDao;
    @Autowired
    private LucenceBo lucenceBo;
    @Autowired
    private BasicInformationQueryBo basicInformationQueryBo;
    private String indexDir = PropDynamicCfg.get("lucence_path");// 索引文件生成目录
    
    Logger log = Logger.getLogger(LuceneServiceImpl.class);
    /**
     * 创建索引文件的接口服务（solr）
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void initIndex(Map temp) throws Exception
    {
//        String url = "http://localhost:8090/solr/menzhenyisheng";
        String url = PropDynamicCfg.get("solrUrl")+"/menzhenyisheng";
        List<Map<String, Object>> listL = lucenceBo.queryDoctorAdviceListL(temp);//检验
        List<Map<String, Object>> listE = lucenceBo.queryDoctorAdviceListE(temp);//检查
        List<Map<String, Object>> list1 = lucenceBo.queryDoctorAdviceList1(temp);//西药
        List<Map<String, Object>> list3 = lucenceBo.queryDoctorAdviceList3(temp);//中药-药品
        List<Map<String, Object>> list8 = lucenceBo.queryDoctorAdviceList8(temp);//中药-方剂
        List<Map<String, Object>> listS = lucenceBo.queryDoctorAdviceListS(temp);//手术
        List<Map<String, Object>> listT = lucenceBo.queryDoctorAdviceListT(temp);//治疗
        List<Map<String, Object>> list4 = lucenceBo.queryDoctorAdviceList4(temp);//材料
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list.addAll(listL);
        list.addAll(listE);
        list.addAll(list1);
        list.addAll(list3);
        list.addAll(list8);
        list.addAll(listS);
        list.addAll(listT);
        list.addAll(list4);
        for (Map<String, Object> map : list)
        {
            map.put("szm", PinyinHelper.getShortPinyin(map.get("bbx05").toString()));
        }
        long a = System.currentTimeMillis();
        BaseSolr.deleteDocumentByQuery(url, "corporationid:"+GlobalVariable.StringIsNull(temp.get("db_corporationid"))+" AND bck01a:"+GlobalVariable.StringIsNull(temp.get("bck01"))+"");
        
        BaseSolr.batchAddDoc(url, list);
        System.out.println("============="+(System.currentTimeMillis()-a)/1000+"秒");
    }
    
    
    
    
    
    
    /**
     * 将测试数据文件写入索引
     * 
     * @param dataDir
     * @throws Exception
     */
    private void createIndex(List<Map<String, Object>> list)
        throws Exception
    {
        Analyzer analyzer = new IKAnalyzer();
//        Analyzer analyzer = new StandardAnalyzer();
        Directory directory = FSDirectory.open(Paths.get(indexDir));
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        indexWriterConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);//索引追加模式
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        for(Map<String, Object> teMap : list)
        {
            teMap.put("shouzimu", PinYinUtilForLucence.getFirstSpell(teMap.get("bbx05").toString()));
//            teMap1.put("pinyin", PinYinUtil.getFullSpell(teMap.get("bbx05").toString()));
            Document document = getDocument(teMap);
            indexWriter.addDocument(document);
        }
        indexWriter.close();
    }
    
    private Document getDocument(Map<String, Object> map)
        throws Exception
    {
        Document document = new Document();
        for(String key : map.keySet())
        {
             document.add(new TextField(key, map.get(key).toString(), Field.Store.YES));
        }
        return document;
    }



    @Override
    public void addIndex(List<Map<String, Object>> list)
        throws Exception
    {
        createIndex(list);
    }



    @Override
    public void updateIndex(List<Map<String, Object>> list)
        throws Exception
    {
    }



    @Override
    public void deleteIndex(List<Map<String, Object>> list)
        throws Exception
    {
    }



    
    private Map<String, Object> documentToMap(Document document)
    {
        Iterator<IndexableField> iterator = document.iterator();
        Map<String, Object> map = new HashMap<String, Object>();
        while (iterator.hasNext())
        {
            IndexableField indexableField = iterator.next();
            map.put(indexableField.name(), document.get(indexableField.name()));
        }
        return map;
    }



    /**
     * 药品、材料规格改变、诊疗项目改变、药库出库
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public ModelVo updateAdvice(Map map)
        throws Exception
    {
        ModelVo mv = new ModelVo();
        try
        {
            String yiyuanids = GlobalVariable.StringIsNull(map.get("yiyuanids"));
            String[] yiyuanidArr = yiyuanids.split(",");
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            String bda01 = GlobalVariable.StringIsNull(map.get("bda01"));
            int sqlId = 0;
            if("1,2".indexOf(bda01)>=0)
            {
                sqlId = 10000057;
            }
            else if("3".equals(bda01))
            {
                sqlId = 10000058;
            }
            else if("8".equals(bda01))
            {
                sqlId = 10000059;
            }
            else if("L".equals(bda01))
            {
                sqlId = 10000060;
            }
            else if("E".equals(bda01))
            {
                sqlId = 10000061;
            }
            else if("S".equals(bda01))
            {
                sqlId = 10000062;
            }
            else if("4M".indexOf(bda01)>=0)
            {
                sqlId = 10000064;
            }
            else
            {
                sqlId = 10000063;
            }
            for(String yiyuanid : yiyuanidArr)
            {
                int bck01 = GlobalVariable.IntegerIsNull(map.get("bck01"), 0);
                 String bby01s = GlobalVariable.StringIsNull(map.get("bby01"));
                 bby01s = bby01s.replaceAll(",", " ");
               /* String[] bby01Arr = bby01s.split(",");
                String bby01 = "";
                for(String temp : bby01Arr)
                {
                    bby01 += "OR bby01: "+temp+" ";
                }
                bby01 = bby01.substring(2);*/
                //先删除
                String condition = "";
                if("12".indexOf(bda01)>=0)
                {
                    condition += "(bda01:1 OR bda01:2) AND bby01:("+bby01s+") AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                    if(bck01!=0)
                    {
                        condition +=" AND bck01:"+bck01;
                    }
                }
                else if("3".indexOf(bda01)>=0)
                {
                    condition += "bda01:3 AND bby01:("+bby01s+") AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                    if(bck01!=0)
                    {
                        condition +=" AND bck01:"+bck01;
                    }
                }
                else if("4M".indexOf(bda01)>=0)
                {
                    condition += "(bda01:4 OR bda01:M) AND bby01:("+bby01s+") AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                    if(bck01!=0)
                    {
                        condition +=" AND bck01:"+bck01;
                    }
                }
                else
                {
                    condition += "bda01:"+bda01+" AND bbx01:"+GlobalVariable.StringIsNull(map.get("bbx01"))+" AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                }
                BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl")+"/menzhenyisheng", condition);
                log.info("solr--delete------condition===="+condition);
                //再新增或者修改
                map.put("dbtype", "'"+map.get("dbtype")+"'");
                map.put("yiyuanid", "'"+yiyuanid+"'");
                map.put("bda01", "'"+bda01+"'");
                map.put("sqlId", sqlId);
                List<Map<String, Object>> list = (List<Map<String, Object>>)basicInformationQueryBo.queryBase(map).getList();
                resultList.addAll(list);
            }
            for(Map<String, Object> temp : resultList)
            {
                temp.put("szm", PinyinHelper.getShortPinyin(temp.get("bbx05").toString()));
            }
            if (!resultList.isEmpty())
            {
                BaseSolr.batchAddDoc(PropDynamicCfg.get("solrUrl") + "/menzhenyisheng", resultList);
            }
            log.info("updateAdvice--------solr--add/update------数量===="+resultList.size());
            mv.setResult(StaticKeys.OH_SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mv.setResult(StaticKeys.OH_FALSE);
        }
        return mv;
    }



    /**
     * 删除索引
     */
    @Override
    public ModelVo deleteAdvice(Map<String, Object> map)
        throws Exception
    {
        ModelVo mv = new ModelVo();
        try
        {
            String yiyuanids = GlobalVariable.StringIsNull(map.get("yiyuanids"));
            String[] yiyuanidArr = yiyuanids.split(",");
            for (String yiyuanid : yiyuanidArr)
            {
                String bda01 = GlobalVariable.StringIsNull(map.get("bda01"));
                String condition = "";
                if("12".indexOf(bda01)>=0)
                {
                    condition += "(bda01:1 OR bda01:2) AND bby01:"+GlobalVariable.StringIsNull(map.get("bby01"))
                    +" AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                }
                if("3".indexOf(bda01)>=0)
                {
                    condition += "bda01:3 AND bby01:"+GlobalVariable.StringIsNull(map.get("bby01"))
                    +" AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                }
                else if("4M".indexOf(bda01)>=0)
                {
                    condition += "(bda01:4 OR bda01:M) AND bby01:"+GlobalVariable.StringIsNull(map.get("bby01"))
                    +" AND corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                }
                else
                {
                    condition = "bda01:"+bda01+" bbx01:"+GlobalVariable.StringIsNull(map.get("bbx01"))
                    +" corporationid:"+(map.get("dbtype")==null?"null":map.get("dbtype").toString())+yiyuanid;
                }
                BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl")+"/menzhenyisheng", condition);
                log.info("deleteAdvice----------solr--delete------condition===="+condition);
            }
            mv.setResult(StaticKeys.OH_SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mv.setResult(StaticKeys.OH_FALSE);
        }
        return mv;
    }



    /**
     * 药品参考
     */
    @Override
    public void initYaopincankaoIndex()
        throws Exception
    {
        String url = PropDynamicCfg.get("solrUrl")+"/yaopincankao";
        Map hashMap = new HashMap();
        List<Map<String, Object>> list = lucenceBo.initYaopincankaoIndex(hashMap);
        BaseSolr.batchAddDoc(url, list);
    }



    /**
     * 疾病索引初始化
     */
    @Override
    public void initzhenduanIndex(Map temp)
        throws Exception
    {
        String url = PropDynamicCfg.get("solrUrl")+"/menzhenzhenduan";
        temp.put("txt", "%%");
        List<Map<String, Object>> list = cliDoctorDao.queryForList("CliDoctor.queryJibingByText1", temp);
        for(Map<String, Object> map : list)
        {
            map.put("id", map.get("bak01"));
        }
        BaseSolr.deleteDocumentByQuery(url, "corporationid:"+GlobalVariable.StringIsNull(temp.get("db_corporationid")));
        log.info("initzhenduanIndex------solr-------delete--疾病------数量=="+list.size());
        if (list!=null && list.size()>0)
        {
            BaseSolr.batchAddDoc(url, list);
        }
        log.info("initzhenduanIndex------solr-------init--疾病------数量=="+list.size());
    }



    /**
     * 查询solr
     */
    @Override
    public ModelVo queryAdviceBySolr(Map<String, Object> paramsObj)
        throws Exception
    {
        ModelVo mv = new ModelVo();
        try
        {
            List<Map<String, Object>> list = BaseSolr.querySolr(paramsObj.get("url").toString(), paramsObj);
            mv.setList(list);
            mv.setResult(StaticKeys.OH_SUCCESS);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mv.setResult(StaticKeys.OH_FALSE);
        }
        return mv;
    }



    /**
     * 医保疾病索引初始化
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void inityibaozhenduanIndex(Map temp)
        throws Exception
    {
        String url = PropDynamicCfg.get("solrUrl")+"/menzhenyibaozhenduan";
        temp.put("txt", "%%");
        List<Map<String, Object>> list = cliDoctorDao.queryForList("Treatment.yibaoJibingList", temp);
        for(Map<String, Object> map : list)
        {
            map.put("szm", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(map.get("iad04"))));
        }
        BaseSolr.deleteDocumentByQuery(url, "corporationid:"+GlobalVariable.StringIsNull(temp.get("db_corporationid")));
        log.info("inityibaozhenduanIndex------solr-------delete--医保疾病------数量=="+list.size());
        if (list!=null && list.size()>0)
        {
            BaseSolr.batchAddDoc(url, list);
        }
        log.info("inityibaozhenduanIndex------solr-------init--医保疾病------数量=="+list.size());
    }






    /**
     * 初始化solr索引 -all
     */
    @Override
    public ModelVo initClinicAdviceSolr(Map map)
        throws Exception
    {
        //医嘱
        //遍历医院id
        String yiyuanids = GlobalVariable.StringIsNull(map.get("yiyuanids"));
        log.info("yiyuanids---------"+yiyuanids);
        String[] yiyuanidArr = yiyuanids.split(",");
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> zhenduanList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> zhenduanList1 = new ArrayList<Map<String, Object>>();
        int[] sqlArr = new int[]{10000066,10000067,10000068,10000069,10000070,10000071,10000072,10000073};
        Map<String, Object> temp1 = new HashMap<>();//医嘱参数
        Map<String, Object> temp2 = new HashMap<>();//疾病参数
        for(String yiyuanid : yiyuanidArr)
        {
            temp1.put("dbtype", "'"+map.get("dbtype")+"'");
            temp1.put("yiyuanid", "'"+yiyuanid+"'");
            for(int sqlId : sqlArr)
            {
                temp1.put("sqlId", sqlId);
                List<Map<String, Object>> list = (List<Map<String, Object>>)basicInformationQueryBo.queryBase(temp1).getList();
                resultList.addAll(list);
            }
            
            temp2.put("corporationid", ""+map.get("dbtype")+yiyuanid);
            //转换参数 dbtype添加单引号

            log.info("corporationid---------"+temp2.get("corporationid"));
            //疾病
//            initzhenduanIndex(temp2);
            List<Map<String, Object>> list1 = cliDoctorDao.queryForList("CliDoctor.queryJibingByText1", temp2);

            zhenduanList.addAll(list1);
            //医保疾病
//            inityibaozhenduanIndex(temp2);
            List<Map<String, Object>> list2 = cliDoctorDao.queryForList("Treatment.yibaoJibingList", temp2);
            zhenduanList1.addAll(list2);
            BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl") + "/menzhenyisheng", "corporationid:"+map.get("dbtype")+"\\"+yiyuanid+"");
            BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl") + "/menzhenzhenduan", "corporationid:"+map.get("dbtype")+"\\"+yiyuanid+"");
            BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl") + "/menzhenyibaozhenduan", "corporationid:"+map.get("dbtype")+"\\"+yiyuanid+"");
        }
        for(Map<String, Object> temp : resultList)
        {
            temp.put("szm", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(temp.get("bbx05"))));
        }
        for(Map<String, Object> temp11 : zhenduanList)
        {
            String id = GlobalVariable.StringIsNull(temp11.get("corporationid"))+ temp11.get("bak01");
            temp11.put("id", id );
        }
        for(Map<String, Object> temp21 : zhenduanList1)
        {
            temp21.put("szm", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(temp21.get("iad04"))));
        }

        log.info("solr-delete---------"+"*:*");
        if (resultList!=null && resultList.size()>0)
        {
            BaseSolr.batchAddDoc(PropDynamicCfg.get("solrUrl") + "/menzhenyisheng", resultList);
        }
        log.info("initClinicAdviceSolr------solr-------init--医嘱------数量=="+resultList.size());
        if (zhenduanList!=null && zhenduanList.size()>0)
        {
            BaseSolr.batchAddDoc(PropDynamicCfg.get("solrUrl") + "/menzhenzhenduan", zhenduanList);
        }
        log.info("initClinicAdviceSolr------solr-------init--诊断------数量=="+zhenduanList.size());
        if (zhenduanList1!=null && zhenduanList1.size()>0)
        {
            BaseSolr.batchAddDoc(PropDynamicCfg.get("solrUrl") + "/menzhenyibaozhenduan", zhenduanList1);
        }
        log.info("initClinicAdviceSolr------solr-------init--医保诊断------数量=="+zhenduanList1.size());
        ModelVo mv = new ModelVo();
        mv.setResult(StaticKeys.OH_SUCCESS);
        return mv;
    }


    /**
     * 适用于本规格下的项目规格修改--按类型重新初始化
     */
    @Override
    public ModelVo updateAdviceByBda01(Map<String, Object> map)
        throws Exception
    {
        //医嘱
        //遍历医院id
        String yiyuanids = GlobalVariable.StringIsNull(map.get("yiyuanids"));
        String[] yiyuanidArr = yiyuanids.split(",");
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        String bda01 = GlobalVariable.StringIsNull(map.get("bda01"));
        String bda01s = "";
        int[] sqlArr = new int[]{};
        if("12".indexOf(bda01)>=0)
        {
            sqlArr = new int[]{10000066};
            bda01s = "(bda01:1 OR bda01:2)";
        }
        if("3".indexOf(bda01)>=0)
        {
            sqlArr = new int[]{10000067,10000068};
            bda01s = "(bda01:3 OR bda01:8)";
        }
        else if("4M".indexOf(bda01)>=0)
        {
            sqlArr = new int[]{10000073};
            bda01s = "(bda01:4 OR bda01:M)";
        }
        
        Map<String, Object> temp1 = new HashMap<>();//医嘱参数
        Map<String, Object> temp2 = new HashMap<>();//疾病参数
        for(String yiyuanid : yiyuanidArr)
        {
            temp1.put("dbtype", "'"+map.get("dbtype")+"'");
            temp1.put("yiyuanid", "'"+yiyuanid+"'");
            for(int sqlId : sqlArr)
            {
                temp1.put("sqlId", sqlId);
                List<Map<String, Object>> list = (List<Map<String, Object>>)basicInformationQueryBo.queryBase(temp1).getList();
                resultList.addAll(list);
            }
            temp2.put("db_corporationid", map.get("dbtype")+"\\"+yiyuanid);
            String condition = "corporationid:"+temp2.get("db_corporationid")+" AND "+bda01s;
            BaseSolr.deleteDocumentByQuery(PropDynamicCfg.get("solrUrl") + "/menzhenyisheng", condition);
            log.info("solr-delete---------"+condition);
        }
        for(Map<String, Object> temp : resultList)
        {
            temp.put("szm", PinyinHelper.getShortPinyin(GlobalVariable.StringIsNull(temp.get("bbx05"))));
        }
        BaseSolr.batchAddDoc(PropDynamicCfg.get("solrUrl") + "/menzhenyisheng", resultList);
        log.info("updateAdviceByBda01----solr-------init--医嘱------数量=="+resultList.size());
        ModelVo mv = new ModelVo();
        mv.setResult(StaticKeys.OH_SUCCESS);
        return mv;
    }


    
}